import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios';

// 创建 axios 实例
const http: AxiosInstance = axios.create({
    baseURL: process.env.REACT_APP_API_BASE_URL || '/api', // 基础 URL
    timeout: 10000, // 请求超时时间
    headers: {
        'Content-Type': 'application/json', // 默认请求头
    },
});

// 请求拦截器
http.interceptors.request.use(
    (config) => {
        // 在发送请求之前做些什么，例如添加 token
        const token = localStorage.getItem('token');
        if (token) {
            config.headers = config.headers || {};
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 响应拦截器
http.interceptors.response.use(
    (response: AxiosResponse) => {
        // 对响应数据做点什么
        const {code, msg} = response.data;
        if (code === 500) {
            const msgs = msg || '服务器内部错误';
            const apiurl = response.request.responseURL || '未知接口';
            window.location.href = `/500?msg=${encodeURIComponent(msgs)}&apiurl=${encodeURIComponent(apiurl)}`;
            return Promise.reject(new Error(msg));
        }
        return response.data;
    },
    (error) => {
        // 对响应错误做点什么
        if (error.response) {
            console.log(error);
            const path = error.request.responseURL;

            switch (error.response.status) {
                case 401:
                    // 未授权，跳转到登录页
                    window.location.href = '/login';
                    break;
                case 403:
                    // 禁止访问，跳转到 403 页并传递 path
                    window.location.href = `/403?path=${encodeURIComponent(path)}`;
                    break;
                case 404:
                    // 未找到，跳转到 404 页并传递 path
                    window.location.href = `/404?path=${encodeURIComponent(path)}`;
                    break;
                case 500:
                    // 服务器错误，跳转到 500 页并传递 msg 和 apiurl
                    const msg = error.response.data?.msg || '服务器内部错误';
                    const apiurl = error.request.responseURL || '未知接口';
                    window.location.href = `/500?msg=${encodeURIComponent(msg)}&apiurl=${encodeURIComponent(apiurl)}`;
                    break;
                case 500:
                    // 服务器错误，跳转到 500 页并传递 path
                    window.location.href = `/500?path=${encodeURIComponent(path)}`;
                    break;
                default:
                    break;
            }
        }
        return Promise.reject(error);
    }
);

export default http;
